const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 3000;

// 读取设置文件
let keywordSettings = {};
const settingsFilePath = path.join(__dirname,'settings.json');
if (fs.existsSync(settingsFilePath)) {
    const settingsData = fs.readFileSync(settingsFilePath, 'utf8');
    keywordSettings = JSON.parse(settingsData);
} else {
    // 默认设置
    keywordSettings = {
        extraction: {
            customerPartNumber: [6, 10],
            factoryPartNumber: [11, 15],
            batchNumber: [16, 20],
            quantity: [21, 25]
        }
    };
}

app.use(express.json());
app.use(express.static(path.join(__dirname)));

// 获取设置
app.get('/settings', (req, res) => {
    res.json(keywordSettings);
});

// 保存设置
app.post('/settings', (req, res) => {
    const settings = req.body;
    fs.writeFile(settingsFilePath, JSON.stringify(settings), 'utf8', (err) => {
        if (err) {
            console.error('保存设置时出错:', err);
            res.status(500).send(`保存设置时出错: ${err.message}`);
        } else {
            keywordSettings = settings;
            res.status(200).send('设置保存成功');
        }
    });
});

// 检查扫码内容是否有连续5位以上相同字段
function hasConsecutiveMatch(str1, str2) {
    for (let i = 0; i <= str1.length - 5; i++) {
        const substr = str1.slice(i, i + 5);
        if (str2.includes(substr)) {
            return true;
        }
    }
    return false;
}

// 检查扫码内容是否匹配
app.post('/check', (req, res) => {
    const { scan1, scan2 } = req.body;
    const match = hasConsecutiveMatch(scan1, scan2);
    console.log('Scan 1:', scan1, 'Scan 2:', scan2, 'Match:', match);
    res.json({ match });
});

// 保存扫码数据到 CSV 文件
app.post('/save', (req, res) => {
    const { scan1, scan2 } = req.body;
    let selectedScan = scan1.length >= scan2.length ? scan1 : scan2;

    const now = new Date();
    const year = String(now.getFullYear()).slice(-2);
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    const dir = path.join(__dirname, year, month);
    const filename = `${year}${month}${day}.csv`;

    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }

    const filePath = path.join(dir, filename);
    const extraction = keywordSettings.extraction;

    const getValue = (start, end) => {
        if (start < 0 || end > selectedScan.length || start >= end) {
            return '';
        }
        return selectedScan.slice(start, end);
    };

    const customerPartNumber = getValue(extraction.customerPartNumber[0], extraction.customerPartNumber[1]);
    const factoryPartNumber = getValue(extraction.factoryPartNumber[0], extraction.factoryPartNumber[1]);
    const batchNumber = getValue(extraction.batchNumber[0], extraction.batchNumber[1]);
    const quantity = getValue(extraction.quantity[0], extraction.quantity[1]);

    // 中文表头
    const headers = '日期,客户零件号,厂内零件号,批次号,数量\n';
    const data = `${month}/${day} ${hours}:${minutes}:${seconds},${customerPartNumber},${factoryPartNumber},${batchNumber},${quantity}\n`;

    const bom = '\ufeff';
    if (!fs.existsSync(filePath)) {
        fs.writeFileSync(filePath, bom + headers, 'utf8');
    }
    fs.appendFile(filePath, data, 'utf8', (err) => {
        if (err) {
            console.error('保存文件时出错:', err);
            res.status(500).send('保存文件时出错');
        } else {
            res.status(200).send('保存成功');
        }
    });
});

app.listen(port, () => {
    console.log(`服务器运行在端口 ${port}`);
});    